import pdb
import subprocess
import threading

from django.contrib import admin
from .models import *


class ConfigAdmin(admin.ModelAdmin):
    list_display = ('name', 'model', 'base_url', 'timeout')
    search_fields = ('name', 'model')


def execute_command(command):
    result = subprocess.run(command, shell=True, capture_output=True)
    print(f"命令: {command}")
    print(f"输出: {result}")


def run_task(obj):
    # 获取ai调用参数
    base_url = obj.config.base_url
    api_key = obj.config.api_key
    model = obj.config.model
    book = obj.book.path
    file_format = obj.target_file_type
    task_id = obj.id
    language = obj.language
    # 执行翻译
    main = r".\extral_apps\ai_translator\main.py "
    cmd = fr"python {main} --model_type OpenAIModel --openai_base_url  {base_url} --openai_api_key {api_key} --openai_model {model} --book {book} --file_format {file_format} --task_id {task_id} --language {language}"
    proc = subprocess.Popen(cmd, shell=True)
    proc.communicate()
    # thread = threading.Thread(target=execute_command, args=(cmd,))
    # thread.start()
    # thread.join()  # 等待线程执行完毕
    print(cmd)


@admin.action(description='开始翻译')
def start_translation(modeladmin, request, queryset):
    for obj in queryset:
        obj.status = '翻译中'
        try:
            run_task(obj)
        except Exception as e:
            print(e)
            obj.status = '翻译失败'
        modeladmin.message_user(request, f"{obj.task_name} 翻译任务已开始")


class TranslationAdmin(admin.ModelAdmin):
    list_editable = ('config', 'book', 'language', 'target_file_type')
    list_display = ('task_name', 'config', 'book', 'language', 'target_file_type', 'result_file', 'status')
    actions = [start_translation]


admin.site.register(Config, ConfigAdmin)
admin.site.register(Translation, TranslationAdmin)
